<template>
    <div class="m_right">
        <p></p>
        <div class="mem_tit">商品添加</div>
        <table class="order-wrapper">
            <tr>
                <td>一级分类：</td>
                <td>
                    <select v-model="categoryLevel1Id" @change="cat1Change">
                        <option disabled value="">请选择</option>
                        <option v-for="c in cat1List" :key="c.id" :value="c.id">
                            {{ c.name }}
                        </option>
                    </select>
                    <span v-if="!valid.categoryValid" class="error-tip">请选择一级分类</span>
                </td>
            </tr>
            <tr v-if="hasLevel2">
                <td>二级分类：</td>
                <td>
                    <select v-model="categoryLevel2Id" @change="cat2Change" :disabled="!categoryLevel1Id">
                        <option disabled value="">请选择</option>
                        <option v-for="c in cat2List" :key="c.id" :value="c.id">
                            {{ c.name }}
                        </option>
                    </select>
                    <span v-if="!valid.categoryValid" class="error-tip">请选择二级分类</span>
                </td>
            </tr>
            <tr v-if="hasLevel3">
                <td>三级分类：</td>
                <td>
                    <select v-model="categoryLevel3Id" :disabled="!categoryLevel2Id">
                        <option disabled value="">请选择</option>
                        <option v-for="c in cat3List" :key="c.id" :value="c.id">
                            {{ c.name }}
                        </option>
                    </select>
                    <span v-if="!valid.categoryValid" class="error-tip">请选择三级分类</span>
                </td>
            </tr>
            <tr>
                <td>商品名称：</td>
                <td>
                    <input type="text" name="name" v-model="name" @blur="checkname()" @focus="clearNameError()">(必填)
                    <span v-if="!valid.nameValid" class="error-tip">请填写商品名称</span>
                </td>
            </tr>
            <tr>
                <td>商品图片：</td>
                <td>
                    <img :src="previewImage" width="70px">
                    <input type="file" name="file" @change="handleSelectImg" ref="fileInput">
                </td>
            </tr>
            <tr>
                <td>单价：</td>
                <td>
                    <input type="number" name="price" v-model="price" @blur="checkprice()" @focus="clearPriceError()">
                    <span v-if="!valid.priceValid" class="error-tip">请正确填写商品价格</span>
                </td>
            </tr>
            <tr>
                <td>库存：</td>
                <td>
                    <input type="number" name="stock" v-model="stock" @blur="checkstock()" @focus="clearStockError()">
                    <span v-if="!valid.stockValid" class="error-tip">请正确填写商品库存</span>
                </td>
            </tr>
            <tr>
                <td>描述：</td>
                <td>
                    <textarea name="description" @blur="checkdescription()" @focus="clearDescriptionError()" cols="55"
                        rows="10" v-model="description"></textarea>
                    <span v-if="!valid.descriptionValid" class="error-tip">请填写商品描述</span>
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="submit" value="确认添加" @click="submitForm()">&nbsp;&nbsp;
                    <input type="button" value="重置" @click="resetForm()">&nbsp;&nbsp;
                    <input type="button" value="返回" @click="backProList()">
                </td>
            </tr>
        </table>
    </div>
</template>

<script>

export default {
    name: 'MemberProductAddRight',
    computed: {
        // 是否有二级
        hasLevel2() {
            if (!this.categoryLevel1Id) return false;
            const node = this.treeData.find(n => n.id === this.categoryLevel1Id);
            return !!(node && node.children && node.children.length);
        },
        // 当前二级节点下是否有三级
        hasLevel3() {
            if (!this.categoryLevel2Id) return false;
            const node = this.cat2List.find(n => n.id === this.categoryLevel2Id);
            return !!(node && node.children && node.children.length);
        }
    },
    data() {
        return {
            name: '',
            previewImage: 'http://192.168.144.183:9090/easybuyImages/null.png',
            price: '',
            stock: '',
            description: '',
            file: null,     // 把当前文件存下来，后续上传用
            //校验数据是否合法
            valid: {
                nameValid: true,
                priceValid: true,
                stockValid: true,
                descriptionValid: true,
                fileOK: false,
                categoryValid: true
            },
            // 获取选择框
            // 以下 3 个是最终提交用的 id
            categoryLevel1Id: '',
            categoryLevel2Id: '',
            categoryLevel3Id: '',

            // 商品分级数据
            cat1List: [],   // 一级
            cat2List: [],   // 二级
            cat3List: [],   // 三级

            // 返回的树形数据
            treeData: []
        }
    },
    methods: {
        // 获取一级数据
        getRootCategroies() {
            this.$axios.get('/selectRootCategories').then(rs => {
                if (rs.data.code === 5200) {
                    this.treeData = rs.data.allCategoryWithChild
                    this.cat1List = this.treeData
                }
            })
        },

        // 选择了一级展示二级数据
        cat1Change() {
            this.categoryLevel2Id = ''
            this.categoryLevel3Id = ''
            this.cat2List = []
            this.cat3List = []
            const node = this.treeData.find(n => n.id === this.categoryLevel1Id)
            if (node && node.children) {
                this.cat2List = node.children
            }
        },

        // 选择了二级，展示三级数据
        cat2Change() {
            this.categoryLevel3Id = ''
            this.cat3List = []
            const node = this.cat2List.find(n => n.id === this.categoryLevel2Id)
            if (node && node.children) {
                this.cat3List = node.children
            }
        },
        handleSelectImg(e) {
            const file = e.target.files[0];
            // 1. 必须上传文件
            if (!file) {
                alert('请上传商品图片');
                e.target.value = '';
                this.previewImage = 'http://192.168.144.183:9090/easybuyImages/null.png';
                return;
            }

            // 2. 必须是图片
            if (!file.type.startsWith('image/')) {
                alert('只能上传图片格式（如 jpg、png、gif）');
                e.target.value = '';
                this.previewImage = 'http://192.168.144.183:9090/easybuyImages/null.png';
                return;
            }

            // 3. 大小 ≤ 2 MB
            const maxSize = 2 * 1024 * 1024; // 2MB 转字节
            if (file.size > maxSize) {
                alert('图片大小不能超过 2MB');
                e.target.value = '';
                this.previewImage = 'http://192.168.144.183:9090/easybuyImages/null.png';
                return;
            }
            this.file = file
            this.valid.fileOK = true
            // 生成本地临时 URL 并赋值
            this.previewImage = URL.createObjectURL(file)
        },
        // 重置表单
        resetForm() {
            this.name = ''
            // 1. 清空文件域
            this.$refs.fileInput.value = ''
            this.previewImage = 'http://192.168.144.183:9090/easybuyImages/null.png'
            this.price = ''
            this.stock = ''
            this.description = ''
        },
        // 校验
        // 专门校验分类层级 
        checkCategory() {
            if (!this.categoryLevel1Id) {
                this.valid.categoryValid = false;
                return false;
            }
            if (this.hasLevel2 && !this.categoryLevel2Id) {
                this.valid.categoryValid = false;
                return false;
            }
            if (this.hasLevel3 && !this.categoryLevel3Id) {
                this.valid.categoryValid = false;
                return false;
            }
            this.valid.categoryValid = true;
            return true;
        },
        checkname() {
            this.valid.nameValid = !!this.name.trim()
        },
        checkprice() {
            this.valid.priceValid = !!this.price.trim()
            this.valid.priceValid = this.price > 0
        },
        checkstock() {
            const stockNum = Number(this.stock);
            this.valid.stockValid = !!this.stock.trim() && stockNum > 0 && Number.isInteger(stockNum);
        },
        checkdescription() {
            this.valid.descriptionValid = !!this.description.trim()
        },
        // 获取焦点清除错误信息
        clearNameError() {
            this.valid.nameValid = true
        },
        clearPriceError() {
            this.valid.priceValid = true
        },
        clearStockError() {
            this.valid.stockValid = true
        },
        clearDescriptionError() {
            this.valid.descriptionValid = true
        },
        // 提交表单
        submitForm() {
            // 校验
            this.checkname()
            this.checkprice()
            this.checkstock()
            this.checkdescription()
            this.checkCategory()
            if (!this.valid.nameValid || !this.valid.priceValid || !this.valid.stockValid || !this.valid.descriptionValid || !this.valid.fileOK || !this.valid.categoryValid) {
                alert('请填写正确商品的信息')
                return
            }
            // 校验通过，提交表单
            // 2. 组装 JSON Blob
            const productJson = {
                name: this.name,
                price: this.price,
                stock: this.stock,
                description: this.description,
                categoryLevel1Id: this.categoryLevel1Id,
                categoryLevel2Id: this.categoryLevel2Id || 0,
                categoryLevel3Id: this.categoryLevel3Id || 0
            };
            const productBlob = new Blob([JSON.stringify(productJson)], { type: 'application/json' });

            // 3. 组装 FormData
            const fd = new FormData();
            fd.append('product', productBlob);
            fd.append('file', this.file);
            this.$axios({
                url: '/addProduct',
                method: 'post',
                data: fd,
                header: {
                    'Content-Type': 'multipart/form-data'
                }
            }).then(rs => {
                console.log("商品添加", rs)
                if (rs.data.code === 5200) {
                    this.$emit('changeView', 'MemberProductListRight');
                } else {
                    alert("添加商品失败")
                }
            })
        },
        backProList() {
            this.$emit('changeView', 'MemberProductListRight');
        }
    },
    mounted() {
        this.getRootCategroies()
    }

}

</script>


<style scoped>
/* —— 订单相关：宽度 85% 并居中 —— */
.order-wrapper {
    width: 85%;
    margin: 20px auto;
    /* 居中 */
    border: 1px solid #dcdfe6;
    /* 新增：外边框 */
    border-radius: 4px;
    /* 可选：圆角更美观 */
    padding: 15px;
    /* 可选：让边框与内容留点空隙 */
    border-collapse: collapse;
    /* 合并边框，避免双线 */
}

.order-wrapper td:first-child {
    width: 30%;
    text-align: right;
    padding-right: 10px;
    /* 可选：让文字和右边的内容有些间距 */
}

/* 统一给所有单元格加边框 */
.order-wrapper td,
.order-wrapper th {
    border: 1px solid #ccc;
    padding: 6px 8px;
    /* 让文字不贴边 */
}

/* 第一个 td：30% 宽 + 文字靠右 */
.order-wrapper td:first-child {
    width: 30%;
    text-align: right;
    padding-right: 10px;
}

/* 错误提示 */
input.error,
textarea.error {
    border: 1px solid #ff4e00;
}

.error-tip {
    color: #ff4e00;
    font-size: 12px;
    margin-left: 6px;
}
</style>